import { Ref, onMounted, ref } from "vue";
import { getAction } from "@/command/netTool";
import { IUrlParams } from "./index";
import { useDetail } from "@/hooks";
import { IDetailPageListConfig, IDetailResult } from "./detail";

interface IFetchPageList {
  pageNo?: number;
  total?: number;
  pages?: number;
  pageSize?: number;
  isClear?: boolean;
}

export interface IFetchPageListConfig {
  getPage: (options: IFetchPageList) => void;
  getParams: () => any;
  next: () => void;
  prev: () => void;
  reset: (params?: any) => void;
  isInit?: boolean;
  loading: Ref<boolean>;
  finished: Ref<boolean>;
}

interface IUseListParams {
  isPage?: boolean;
}

export type IFetchResult = [Ref<any[]>, IFetchPageListConfig];

export const useList = (
  urlParams: IUrlParams
): [Ref<any[]>, IDetailPageListConfig] => {
  const [list, listControl] = useDetail(urlParams, []);
  return [list, listControl];
};
export const usePage = (urlParams: IUrlParams): IFetchResult => {
  const { url } = urlParams;
  const list = ref([]);
  const listParams = ref<IFetchPageList>({ pageNo: 0, pageSize: 10 } as any);
  const current = ref(1);
  const finished = ref(false);
  const loading = ref(false);

  onMounted(() => {
    getPage({ pageNo: 1, pageSize: 10 });
  });
  const next = () => {
    console.log("next");
    getPage({ pageNo: listParams.value.pageNo! + 1 });
  };
  const prev = () => {
    getPage({ pageNo: current.value - 1 });
  };
  const reset = (params: any) => {
    getPage({ pageNo: 1, pageSize: 10, ...params, isClear: true });
  };

  const getPage = (params: IFetchPageList = { pageNo: 1, pageSize: 10 }) => {
    if (url && !loading.value) {
      loading.value = true;
      getAction(url, {
        pageNo: params.pageNo,
        pageSize: 10,
        ...listParams.value,
        ...params,
      })
        .then((e) => {
          loading.value = false;
          if (params.isClear) {
            list.value = e.list;
            listParams.value = params;
            finished.value = list.value.length == e.count;
          } else {
            if (e.count == 0) {
              finished.value = true;
              list.value = [];
            } else {
              list.value = list.value.concat(e.list);
              finished.value = list.value.length == e.count;
            }
            listParams.value = params;
          }
        })
        .catch(() => {
          loading.value = false;
        });
    }
  };
  const getParams = () => {
    return listParams;
  };
  return [list, { getPage, next, prev, reset, getParams, finished, loading }];
};

export const useListPage = (params: any, isPage: boolean) => {
  return isPage == true ? usePage(params) : useList(params);
};
